{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "97292ded",
   "metadata": {},
   "outputs": [],
   "source": [
    "import cv2\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fe4fd271",
   "metadata": {},
   "source": [
    "## 测试CV检测图片的轨迹"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "a084ca01",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[255 255 255]\n",
      "<class 'float'> 127.0\n",
      "(array([[[305, 423]],\n",
      "\n",
      "       [[306, 422]],\n",
      "\n",
      "       [[312, 422]],\n",
      "\n",
      "       [[313, 423]],\n",
      "\n",
      "       [[313, 424]],\n",
      "\n",
      "       [[314, 425]],\n",
      "\n",
      "       [[314, 434]],\n",
      "\n",
      "       [[313, 435]],\n",
      "\n",
      "       [[313, 436]],\n",
      "\n",
      "       [[312, 437]],\n",
      "\n",
      "       [[306, 437]],\n",
      "\n",
      "       [[305, 436]],\n",
      "\n",
      "       [[305, 434]],\n",
      "\n",
      "       [[302, 434]],\n",
      "\n",
      "       [[301, 433]],\n",
      "\n",
      "       [[301, 426]],\n",
      "\n",
      "       [[302, 425]],\n",
      "\n",
      "       [[305, 425]]], dtype=int32), array([[[303, 428]],\n",
      "\n",
      "       [[303, 431]],\n",
      "\n",
      "       [[305, 431]],\n",
      "\n",
      "       [[305, 428]]], dtype=int32), array([[[306,  52]],\n",
      "\n",
      "       [[307,  51]],\n",
      "\n",
      "       [[329,  51]],\n",
      "\n",
      "       ...,\n",
      "\n",
      "       [[271,  53]],\n",
      "\n",
      "       [[289,  53]],\n",
      "\n",
      "       [[290,  52]]], dtype=int32)) [[[ 3 -1  2  0]\n",
      "  [-1 -1 -1  1]\n",
      "  [-1  1 -1  0]]]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "-1"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"\"\"用于测试opencv检测图片的轮廓功能\"\"\"\n",
    "import cv2\n",
    "import numpy as np\n",
    "\n",
    "#加载图片\n",
    "img=cv2.imread('combo.png')\n",
    "\n",
    "#查看像素值\n",
    "print(img[0,0])#三通道图\n",
    "gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n",
    "\n",
    "# 二值化处理\n",
    "Ret, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)#类型处理方法\n",
    "print(type(Ret),Ret)\n",
    "#轮廓检测\n",
    "contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n",
    "\n",
    "# 去除外层黑边\n",
    "contours = contours[1:]        # 扔掉 0 号\n",
    "hierarchy  = hierarchy[:, 1:, :]\n",
    "print(contours,hierarchy)\n",
    "\n",
    "output = np.zeros_like(img)\n",
    "#绘制轮廓\n",
    "cv2.drawContours(img, contours, -1, (0, 0, 255), 2)#绘制所有的轮廓\n",
    "cv2.imshow('img',img)\n",
    "cv2.waitKey(0)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5bcfa6f8",
   "metadata": {},
   "source": [
    "## 测试轮廓检测"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "425ebf30",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "21 20\n",
      "(array([420, 420, 421]), array([290, 291, 290]))\n",
      "(441.3333333333333, 310.3333333333333)\n",
      "300.5 431.0\n"
     ]
    }
   ],
   "source": [
    "import cv2 as cv\n",
    "import numpy as np\n",
    "\n",
    "#加载图片\n",
    "img=cv.imread('combo.png')\n",
    "template = cv.imread('src/CAR.png')#需要识别的物体\n",
    "\n",
    "#获取模板图像的尺寸\n",
    "\n",
    "w, h = template.shape[:-1]\n",
    "print(w,h)\n",
    "\n",
    "# 进行模板匹配\n",
    "res = cv.matchTemplate(img, template, cv.TM_CCOEFF_NORMED)\n",
    "\n",
    "# 设置匹配阈值\n",
    "threshold = 0.8\n",
    "\n",
    "# 找到匹配位置\n",
    "loc = np.where(res >= threshold)\n",
    "print(loc)\n",
    "\n",
    "#获取中心位置\n",
    "center = (float(sum(loc[0]) / len(loc[0])) + w, float(sum(loc[1]) / len(loc[1])) + h)\n",
    "print(center)\n",
    "# 在目标图像中标记匹配位置\n",
    "for pt in zip(*loc[::-1]):\n",
    "    cv.rectangle(img, pt, (pt[0] + w, pt[1] + h), (0, 255, 0), 2)#图像，矩形，颜色，线宽\n",
    "for pt in zip(*loc[::-1]): pass\n",
    "print(pt[0] + w/2,pt[1] + h/2)\n",
    "\n",
    "# # --------------- 新增：取车头前方 20×20 ---------------\n",
    "# # 以第一个匹配为例（若有多辆车，自己决定用哪一个）\n",
    "# x1 = pt[0] + 21         # 左上角列 +20\n",
    "# y1 = pt[1]               # 左上角行（车顶）\n",
    "# x2 = x1 + 21             # 横向 20 像素\n",
    "# y2 = y1 + 21             # 纵向 20 像素\n",
    "\n",
    "# print('x1,y1,x2,y2:', x1, y1, x2, y2)\n",
    "\n",
    "# roi = img[y1:y2, x1:x2]  # 车头前 20×20\n",
    "# cv.imshow('Car-Front-20x20', roi)\n",
    "# #图片保存\n",
    "# cv.imwrite('Car-Front-20x20.png', roi)\n",
    "# # ------------------------------------------------------\n",
    "\n",
    "\n",
    "\n",
    "# gray = cv.cvtColor(roi, cv.COLOR_BGR2GRAY)\n",
    "# _, bin = cv.threshold(gray, 60, 255, cv.THRESH_BINARY_INV)  # 黑→白\n",
    "\n",
    "# y_idx, x_idx = np.where(bin == 255)\n",
    "\n",
    "\n",
    "# if x_idx.size == 0:          # 丢线保护\n",
    "#     dx = 0\n",
    "# else:\n",
    "#     cx = x_idx.mean()        # 0~19\n",
    "    \n",
    "#     dx = cx - 9.5            # 窗口中心列\n",
    "    \n",
    "# e = dx / 9.5   # -1 ~ 1\n",
    "\n",
    "\n",
    "# k= 5\n",
    "# delta = k * e  # k 试验取 5~15°\n",
    "\n",
    "\n",
    "# new_angle = delta\n",
    "# print('new_angle:', new_angle)\n",
    "\n",
    "# 显示结果图像\n",
    "cv.imshow('Matched Image', img)\n",
    "cv.waitKey(0)\n",
    "cv.destroyAllWindows()\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "45a4567b",
   "metadata": {},
   "source": [
    "## 设置移动"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "d61c8fe4",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[[255 255 255]\n",
      "  [255 255 255]\n",
      "  [255 255 255]\n",
      "  ...\n",
      "  [255 255 255]\n",
      "  [255 255 255]\n",
      "  [255 255 255]]\n",
      "\n",
      " [[255 255 255]\n",
      "  [255 255 255]\n",
      "  [255 255 255]\n",
      "  ...\n",
      "  [255 255 255]\n",
      "  [255 255 255]\n",
      "  [255 255 255]]\n",
      "\n",
      " [[255 255 255]\n",
      "  [255 255 255]\n",
      "  [255 255 255]\n",
      "  ...\n",
      "  [255 255 255]\n",
      "  [255 255 255]\n",
      "  [255 255 255]]\n",
      "\n",
      " ...\n",
      "\n",
      " [[255 255 255]\n",
      "  [255 255 255]\n",
      "  [255 255 255]\n",
      "  ...\n",
      "  [255 255 255]\n",
      "  [255 255 255]\n",
      "  [255 255 255]]\n",
      "\n",
      " [[255 255 255]\n",
      "  [255 255 255]\n",
      "  [255 255 255]\n",
      "  ...\n",
      "  [255 255 255]\n",
      "  [255 255 255]\n",
      "  [255 255 255]]\n",
      "\n",
      " [[255 255 255]\n",
      "  [255 255 255]\n",
      "  [255 255 255]\n",
      "  ...\n",
      "  [255 255 255]\n",
      "  [255 255 255]\n",
      "  [255 255 255]]]\n"
     ]
    }
   ],
   "source": [
    "\n",
    "\"\"\"用于测试opencv检测图片的轮廓功能\"\"\"\n",
    "import cv2\n",
    "import numpy as np\n",
    "\n",
    "#加载图片\n",
    "img=cv2.imread('combo.png')\n",
    "#查看像素值\n",
    "print(img)#三通道图\n",
    "\n",
    "# 显示图像\n",
    "cv2.imshow(\"Display Window\", img)\n",
    "\n",
    "# 等待按键输入\n",
    "cv2.waitKey(0)\n",
    "\n",
    "# 关闭所有窗口\n",
    "cv2.destroyAllWindows()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "5548a266",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 获取 ROI\n",
    "roi = img[50:150, 50:150]  # 获取 (50,50) 到 (150,150) 的区域\n",
    "\n",
    "# 显示 ROI\n",
    "cv2.imshow(\"ROI\", roi)\n",
    "\n",
    "# 等待按键输入\n",
    "cv2.waitKey(0)\n",
    "\n",
    "# 关闭所有窗口\n",
    "cv2.destroyAllWindows()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "04bb0fe4",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
